package org.example.dingtalkintegrationservice.dingtalk.token;
import lombok.extern.slf4j.Slf4j;
import org.example.dingtalkintegrationservice.exception.DingTalkCallExceptionGroovy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.teaopenapi.models.Config;

import java.util.concurrent.TimeUnit;

/**
 * @author pc
 */
@Component
@Slf4j
public class GetDingToken {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
//    @Value("${spring.data.redis.host}")
//    String redisHost;
//    @Value("${spring.data.redis.port}")
//    int redisPort;
    public  String getTokenFromDingTalk() throws Exception {
        Config config = new Config().setProtocol("https").setRegionId("central");
        var authClient = new Client(config);
        var accessTokenConfig = new GetAccessTokenRequest()
                .setAppKey("dingvnclcjl37jgrgok1")
                .setAppSecret("ttfStLJUDvYyvzfFIV-QYkVm5l33sEm12G065aiHrb-sjWYRNFtFHdVONRr0uRFU");
        var res=authClient.getAccessToken(accessTokenConfig);
        if (res.statusCode!=200){
            throw new DingTalkCallExceptionGroovy(res.toString());
        }
        return res.getBody().getAccessToken();
    }
    public String getTokenFromRedis() {
        try {
//            Jedis jedis = new Jedis(redisHost, redisPort);
            Object value=redisTemplate.opsForValue().get("dingTokenProd");
//            String value = jedis.get("dingToken");
            if (value != null) {
                log.info("getTokenFromRedisSuccess!");
                return value.toString();

            } else {
                String token = getTokenFromDingTalk();
                redisTemplate.opsForValue().set("dingTokenProd", token,7000, TimeUnit.SECONDS);
//                jedis.setex("dingToken", 7000, token);
                return token;
            }
        } catch (Exception e) {
            log.error("getTokenError");
            log.error(e.getMessage());
        }
        return "";
    }
}